from time import time, sleep
from appium import webdriver
import allure
import yaml
# from selenium import webdriver
from appium.webdriver.common.touch_action import  TouchAction


from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:

    _BASE_URL = ''

    def __init__(self,base_driver=None):
        if base_driver:
            self.driver = base_driver
        else:
            # 资源初始化
            # 打开【企业微信】应用
            caps = {}
            caps["platformName"] = "Android"
            caps["appPackage"] = "com.tencent.wework"
            caps["appActivity"] = ".launch.LaunchSplashActivity"
            caps["deviceName"] = "emulator-5554"
            # "True" 是绝对不可以的  要么是"true" 要么是 True
            caps["noReset"] = "true"
            # 创建driver ,与appium server建立连接，返回一个 session
            # driver 变成self.driver 由局部变量变成实例变量，就可以在其它的方法中引用这个实例变量了
            self.driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
            self.driver.implicitly_wait(5)

        # if not self.driver.current_url.startswith("http"):
        #     self.driver.get(self._BASE_URL)

    def do_find(self, by, locator=None):
        #获取单个元素
        if locator:
            return self.driver.find_element(by, locator)
        else:
            return self.driver.find_element(*by)

    def do_finds(self, by, locator=None):
        #获取多个元素
        if locator:
            return self.driver.find_elements(by, locator)
        else:
            return self.driver.find_elements(*by)

    def do_send_keys(self, value, by, locator=None):
        ele = self.do_find(by, locator)
        ele.clear()
        ele.send_keys(value)

    def do_send_files(self, file, by, locator=None):
        ele = self.do_find(by, locator)
        ele.send_keys(file)

    def do_quit(self):
        self.driver.quit()

    #回到首页
    def do_back(self):
        self.driver.keyevent(4)

    def get_screen(self):
        timestamp = int(time())
        image_path = f"./images/image_{timestamp}.PNG"
        #截图
        self.driver.save_screenshot(image_path)
        #将截图放到报告的数据中
        allure.attach.file(image_path,name='picture',attachment_type=allure.attachment_type.PNG)

    def wait_element_until_visible(self, locator:tuple):
        return WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located(locator))

    def do_scroll_bottom(self):
        # self.action = TouchAction(self.driver)
        # self.action.scroll(0,1000)
        # self.action.perform()
        pass

    def do_open_cookie(self):
        with open('../data/cookie.yaml',"r", encoding='u8') as f:
            self.cookie = yaml.safe_load(f)
        return self.cookie


